import java.text.SimpleDateFormat
import ru.niir.goodfil.db.DataExchange
import ru.niir.goodfil.db.GoodfilFactory

class Gf {
  static def gf = GoodfilFactory.instance;
}

def gf() {
  Gf.gf;
}

def ask_number() {
  br = System.in.newReader();
  while (true) {
    print ">>>";
    try {
      return new Integer(br.readLine());
    } catch (NumberFormatException nfe) {
    }
  }
}

def menu_main() {
  print """
    1. 1C Interop
    0. Exit
  """

  int cmd = ask_number();
  if (cmd == 0) exit(0);
}

def menu_interop() {
  println "--- 1C Interop ---";
  println "Actual state       : " + safe({isC1Running()});
  println "Last exchange date : " + safe({lastExchangeDate()});
  println "1C remote failure  : " + safe({isC1RemoteRunning()});
  println "Last rests update  : " + safe({lastRestsUpdate()});;
  println ""
  println "Top 50 logs";
  for (de in gf().getTopDataExchanges(50)) {
    println sprintf("%-5s %-8s %-100s %-9s    %-15s", de.id, de.tableName, dataExchangeDescription(de), dataExchangeStatus(de.exchangeStateId), format(de.creationDate))
  }
}

def format(Date d) {
  new SimpleDateFormat("dd.MM.yyyy HH:mm").format(d);
}

def dataExchangeStatus(int status) {
  switch (status) {
    case 1: "Queued"; break;
    case 2: "Sent"; break;
    case 3: "Accepted"; break;
  }
}

def dataExchangeDescription(DataExchange de) {
  if (de.tableName == "Clients") {
    return gf().getClientById(de.itemId)?.toClientString();
  }
  if (de.tableName == "Orders") {
    o = gf().getOrderById(de.itemId);
    if (o == null || o.deleted) {
      return "Detetion: ${de.itemId}";
    } else {
      gf().countOrderDeliverySum(o);
      gf().countOrderSum(o);
      c = gf().getClientById(o.clientId);
      return o.toClientString(c);
    }
  }
}

print """
--- Welcome to GW Admin Shell ---
"""

menu_interop();


def safe(Closure c) {
  try {
    return c.call();
  } catch (Exception e) {
    return e.message;
  }
}

def isC1Running() {
  ru.niir.goodfil.ui.utils.Process.exists("Goodwill1C.jar");
}

def isC1RemoteRunning() {
  Date ts = lastExchangeDate();

  long l1 = ts.getTime(); // ms
  long l2 = Calendar.getInstance().getTimeInMillis(); // ms
  l1 = l1 / 1000; // s
  l2 = l2 / 1000; // s

  return l2 - l1 < 60 * 2;
}

def lastExchangeDate() {
  new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").parse(new File("/media/1c/errors/time.txt").text);
}

def lastRestsUpdate() {
  return gf.get(".1c.rests.last");
}